package com.uniriho.lxr5002_service.utils;

import com.uniriho.lxr5002_service.Constants;

import java.util.Timer;
import java.util.TimerTask;

public class TimerUtils {

    private Timer mTimer; //计时器，每1秒执行一次任务
    private MyTimerTask mTimerTask; //计时任务
    private boolean isStopTimer = false;
    private TimeListener timeListener;

    private class MyTimerTask extends TimerTask {
        @Override
        public void run() {
            LogUtils.error("TimerUtils", "执行中...");
            // 通知开始GPS定位
            if (!isStopTimer && timeListener != null) {
                LogUtils.error("TimerUtils", "通知定位");
                timeListener.startGPS();
            }
            stopTimer();
        }
    }

    //开始计时
    public void startTimer() {
        isStopTimer = false;

        if (mTimerTask == null) {
            mTimerTask = new MyTimerTask();
        }
        if (mTimer == null) {
            mTimer = new Timer(true);
        }
        mTimer.schedule(mTimerTask, Constants.GPS_TIMER_TIMEOUT, Constants.GPS_TIMER_TIMEOUT); //延时5分钟后执行

    }

    // 停止计时任务
    public void stopTimer() {
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
        if (mTimerTask != null) {
            mTimerTask.cancel();
            mTimerTask = null;
        }
        isStopTimer = true;
    }


    public interface TimeListener {
        void startGPS();
    }

    public void setTimeListener(TimeListener listener) {
        this.timeListener = listener;
    }

}
